import React, { useState, useEffect, useMemo } from "react";
import Web3 from 'web3';
import { useParams, Link, useNavigate } from 'react-router-dom';
import CourseListABI from '../contract/ABIs/CourseList.json';//课程列表合约ABI
import CourseListAddress from '../contract/ADDRESSes/CourseListAddress';//课程列表合约地址
import AdminABI from '../contract/ABIs/Admin.json'; // 管理员合约 ABI
import { Table, Pagination, Input } from "antd";
import AdminNavBar from './nav/AdminNavBar.js'
import Head from './nav/Head.js';


const Admin_CourseManage = () => {
    const [web3, setWeb3] = useState(null);
    // 使用 useParams 获取路由参数中的地址信息
    const { address } = useParams();
    const [CourseRecordList, setCourseRecordList] = useState([]);    //根据课程编号查询课程信息，返回值是8个元素，依次为课程编号、课程名称、课程性质、课程属性、学分、学时、开设学期、考试成绩占比
    const [contractCourseRecordList, setcontractCourseRecordList] = useState(null);
    const [contractAdmin, setcontractAdmin] = useState(null);
    const [isAdmin, setIsAdmin] = useState(false);
    const [IsList, setIsList] = useState(false);//控制是否显示列表

    // 将课程编号状态单独提取出来
    const [originalCourseNumber, setOriginalCourseNumber] = useState('');
    const [courseNumber, setcourseNumber] = useState('');//课程编号
    //更新时使用的变量
    //const [newCourseNumber, setnewCourseNumber] = useState('');//课程编号用来选择更新课程
    const [newSurriculumSystem, setnewSurriculumSystem] = useState('');//课程体系
    const [newCourseName, setnewCourseName] = useState('');//课程名称
    const [newCourseNature, setnewCourseNature] = useState('');//课程性质
    const [newCourseAttribute, setnewCourseAttribute] = useState('');//课程属性
    const [newCredit, setnewCredit] = useState(0);//学分
    const [newContactHour, setnewContactHour] = useState(0);//学时
    const [newSemesterOffered, setnewSemesterOffered] = useState(0);//开设学期
    const [newGradeScale, setnewGradeScale] = useState(0);//考试成绩占比

    const [filteredData, setFilteredData] = useState([]);
    const [searchText, setSearchText] = useState("");
    const [currentPage, setCurrentPage] = useState(1);
    const pageSize = 10; // 每页显示的数据量

    //设置删除课程记录的模态框是否打开
    const [deleteModalOpen, setDeleteModalOpen] = useState(false);
    const navigate = useNavigate();

    const columns = [
        {
            title: '课程体系',
            dataIndex: 'surriculumSystem',
            key: 'surriculumSystem',
            render: (text) => {
                const newText = text.toString(); // 将文本转换为字符串
                return <span style={{ color: 'black' }}>{newText}</span>;
            },
        },
        {
            title: '课程编号',
            dataIndex: 'courseNumber',
            key: 'courseNumber',
            render: (text) => (
                <span style={{ color: 'black' }}>
                    {text}
                </span>
            )
        },
        {
            title: '课程名称',
            dataIndex: 'courseName',
            key: 'courseName',
            render: (text) => (
                <span style={{ color: 'black' }}>
                    {text}
                </span>
            )
        },
        {
            title: '课程性质',
            dataIndex: 'courseNature',
            key: 'courseNature',
            render: (text) => (
                <span style={{ color: 'black' }}>
                    {text}
                </span>
            )
        },
        {
            title: '课程属性',
            dataIndex: 'courseAttribute',
            key: 'courseAttribute',
            render: (text) => (
                <span style={{ color: 'black' }}>
                    {text}
                </span>
            )
        },
        {
            title: '学分',
            dataIndex: 'credit',
            key: 'credit',
            render: (text) => {
                const newText = text.toString(); // 将文本转换为字符串
                return <span style={{ color: 'black' }}>{newText}</span>;
            },
        },
        {
            title: '学时',
            dataIndex: 'contactHour',
            key: 'contactHour',
            render: (text) => {
                const newText = text.toString(); // 将文本转换为字符串
                return <span style={{ color: 'black' }}>{newText}</span>;
            },
        },
        {
            title: '开设学期',
            dataIndex: 'semesterOffered',
            key: 'semesterOffered',
            render: (text) => {
                const newText = text.toString(); // 将文本转换为字符串
                return <span style={{ color: 'black' }}>{newText}</span>;
            },
        },
        {
            title: '考试成绩计算比',
            dataIndex: 'gradeScale',
            key: 'gradeScale',
            render: (text) => {
                const newText = text.toString(); // 将文本转换为字符串
                return <span style={{ color: 'black' }}>{newText}</span>;
            },
        },
        {
            title: '操作',
            key: 'action',
            render: (text, record) => (
                <button className="btn btn-primary btn-lg d-block w-100" type="primary" onClick={() => DeleteCourse(record)}>
                    删除
                </button>
            ),
        },
        {
            title: '操作',
            key: 'action',
            render: (text, record) => (
                <button className="btn btn-primary btn-lg d-block w-100" type="primary" onClick={() => openDeleteModal(record)}>
                    更新
                </button>
            ),
        }
    ];

    useEffect(() => {
        async function init() {
            // 连接到以太坊网络
            if (window.ethereum) {
                const web3Instance = new Web3(window.ethereum);
                try {
                    // 请求用户授权
                    await window.ethereum.enable();
                    setWeb3(web3Instance);

                    // 创建课程记录合约实例
                    const courseListInstance = new web3Instance.eth.Contract(
                        CourseListABI,
                        CourseListAddress
                    );
                    setcontractCourseRecordList(courseListInstance);

                    // 创建管理员合约实例
                    const adminInstance = new web3Instance.eth.Contract(
                        AdminABI,
                        address
                    );
                    setcontractAdmin(adminInstance);

                    // 获取当前用户的以太坊账户地址
                    const accounts = await web3Instance.eth.getAccounts();
                    const currentAddress = accounts[0];
                    // 获取管理员合约的 owner 地址
                    const ownerAddress = await adminInstance.methods.getOwner().call();
                    // 检查当前账户是否是管理员本人
                    setIsAdmin(currentAddress === ownerAddress);

                    // 自动获取学生信息列表
                    await GetAllCourseInfo(web3Instance, courseListInstance);
                } catch (error) {
                    console.error(error);
                }
            } else {
                console.error('请安装以太坊浏览器插件，如 MetaMask');
            }
        }
        init();
    }, [address]);

    //管理员查询课程信息
    const GetAllCourseInfo = async (web3Instance, courseListInstance) => {
        if (courseListInstance) {
            try {
                // 获取当前用户的以太坊账户地址
                const accounts = await web3Instance.eth.getAccounts();
                const fromAddress = accounts[0];
                console.log("fromAddress:", fromAddress);

                const result = await courseListInstance.methods.getAllCourses().call({ from: fromAddress });
                setCourseRecordList(result || []);
                setFilteredData(result || []);
                setIsList(true);//让列表显示出来
                // alert("查询成功")
            } catch (error) {
                console.error(error);
                alert("查询失败")
            }
        }
    };

    //管理员删除课程记录
    const DeleteCourse = async (record) => {
        if (contractCourseRecordList) {
            try {
                // 获取当前用户的以太坊账户地址
                const accounts = await web3.eth.getAccounts();
                const fromAddress = accounts[0];
                console.log("record:", record.courseNumber);
                await contractCourseRecordList.methods.deleteCourse(record.courseNumber).send({ from: fromAddress });
                alert("删除成功！")
                navigate(`/admin/${address}/Admin_credits/Admin_CourseManage`)
            } catch (error) {
                console.error(error);
                alert("删除失败！")
            }
        }
    };


    //打开更新模态框
    const openDeleteModal = (courseRecord) => {
        setOriginalCourseNumber(courseRecord.courseNumber);
        // 依次为课程编号、课程名称、课程性质、课程属性、学分、学时、开设学期、考试成绩占比
        setcourseNumber(courseRecord.courseNumber);
        setnewSurriculumSystem(courseRecord.surriculumSystem);
        setnewCourseName(courseRecord.courseName)
        setnewCourseNature(courseRecord.courseNature)
        setnewCourseAttribute(courseRecord.courseAttribute)
        setnewCredit(Number(courseRecord.credit))
        setnewContactHour(Number(courseRecord.contactHour))
        setnewSemesterOffered(Number(courseRecord.semesterOffered))
        setnewGradeScale(Number(courseRecord.gradeScale))
        setDeleteModalOpen(true);
    };

    //管理员修改课程信息
    const updateCourse = async () => {
        setDeleteModalOpen(false);
        if (contractCourseRecordList) {
            try {
                // 获取当前用户的以太坊账户地址
                const accounts = await web3.eth.getAccounts();
                const fromAddress = accounts[0];
                console.log("fromAddress:", fromAddress, "Input:", courseNumber, newSurriculumSystem, newCourseName, newCourseNature, newCourseAttribute, newCredit, newContactHour, newSemesterOffered, newGradeScale);

                // 调用智能合约的某个函数
                await contractCourseRecordList.methods.modifyCourse(courseNumber, newSurriculumSystem, newCourseName, newCourseNature, newCourseAttribute, newCredit, newContactHour, newSemesterOffered, newGradeScale).send({ from: fromAddress });
                setOriginalCourseNumber(courseNumber)
                alert("修改成功")
                navigate(`/admin/${address}/Admin_credits/Admin_CourseManage`)
            } catch (error) {
                console.error(error);
                alert("修改失败")
            }
        }
    };

    // 处理搜索功能
    const handleSearch = (value) => {
        setSearchText(value);
        if (value === "") {
            setFilteredData(CourseRecordList);
        } else {
            const filtered = CourseRecordList.filter(
                (item) =>
                    item.courseName.toLowerCase().includes(value.toLowerCase())
            );
            setFilteredData(filtered);
        }
        setCurrentPage(1); // 重置为第一页
    };

    // 处理页码改变事件
    const handlePageChange = (page) => {
        setCurrentPage(page);
    };

    // 计算当前页的数据
    const currentPageData = useMemo(() => {
        return filteredData.slice((currentPage - 1) * pageSize, currentPage * pageSize);
    }, [filteredData, currentPage]);


    return (
        <div>
            {/* 如果当前账户不是管理员，则显示提示信息 */}
            {!isAdmin && (<div>您没有权限访问此页面。</div>)}

            {/* 管理员界面 */}
            {isAdmin && (
                <div>
                    <div className="page-wrapper">
                        <div className="main-container" style={{
                            backgroundColor: '#FFFFFF'
                        }}>
                            <AdminNavBar address={address}></AdminNavBar>

                            <div className="app-container">
                                <Head></Head>

                                <div className="app-body">
                                    <div className="container-fluid">
                                        <div>
                                            <main className="page hire-me-page">
                                                <section className="portfolio-block hire-me">

                                                    <div className="container">
                                                        <div className="border rounded border-0 shadow-lg p-3 p-md-5"
                                                            data-bs-theme="light"
                                                            style={{
                                                                backgroundColor: 'rgba(36, 36, 41, 0.6)'
                                                            }}
                                                        >

                                                            <h2>课程列表</h2>
                                                            <div className="mb-3">
                                                                <div className="d-flex justify-content-end mt-3">

                                                                </div>

                                                                {IsList ? (
                                                                    <>
                                                                        <div className="d-flex justify-content-end mt-3">
                                                                            <div className="input-group mb-3" style={{ maxWidth: '300px' }}>
                                                                                <div className="choices">
                                                                                    <button className="btn btn-primary btn-lg d-block w-100" >
                                                                                        <Link to={`/admin/${address}/Admin_credits/Admin_addMultiCourses`} className="choice">添加课程</Link>
                                                                                    </button>
                                                                                </div>
                                                                                <Input.Search
                                                                                    placeholder="搜索课程名..."
                                                                                    value={searchText}
                                                                                    onChange={(e) => handleSearch(e.target.value)}
                                                                                    style={{ marginBottom: 16 }}
                                                                                />
                                                                            </div>
                                                                        </div>
                                                                        <Table
                                                                            dataSource={currentPageData}
                                                                            columns={columns} // 确保你已经定义了columns
                                                                            loading={!CourseRecordList.length}
                                                                            pagination={false}
                                                                        />
                                                                        <Pagination
                                                                            current={currentPage}
                                                                            pageSize={pageSize}
                                                                            total={filteredData.length}
                                                                            onChange={handlePageChange}
                                                                            style={{ marginTop: 16, textAlign: "center" }}
                                                                        />
                                                                    </>
                                                                ) : (
                                                                    <div>No course information available.</div>
                                                                )}


                                                                {deleteModalOpen && (
                                                                    <div className="mb-3">
                                                                        <h2>管理员修改课程信息</h2>
                                                                        {/* 课程编号用来选择更新课程 */}
                                                                        <div className="mb-3">
                                                                            <label className="form-label">正在修改编号为{originalCourseNumber}的课程信息</label>
                                                                        </div>
                                                                        <div className="mb-3">
                                                                            <label className="form-label" htmlFor="name">课程编号</label>
                                                                            <input className="form-control item" id="name" type="text" placeholder="课程编号" value={courseNumber} readOnly />
                                                                        </div>
                                                                        <div className="mb-3">
                                                                            <label className="form-label" htmlFor="name">课程体系</label>
                                                                            <input className="form-control item" id="name" type="text" placeholder="课程体系" value={newSurriculumSystem} onChange={(e) => setnewSurriculumSystem(e.target.value)} />
                                                                        </div>
                                                                        <div className="mb-3">
                                                                            <label className="form-label" htmlFor="name">课程名称</label>
                                                                            <input className="form-control item" id="name" type="text" placeholder="课程名称" value={newCourseName} onChange={(e) => setnewCourseName(e.target.value)} />
                                                                        </div>
                                                                        <div className="mb-3">
                                                                            <label className="form-label" htmlFor="name">课程性质</label>
                                                                            <input className="form-control item" id="name" type="text" placeholder="课程性质" value={newCourseNature} onChange={(e) => setnewCourseNature(e.target.value)} />
                                                                        </div>
                                                                        <div className="mb-3">
                                                                            <label className="form-label" htmlFor="name">课程属性</label>
                                                                            <input className="form-control item" id="name" type="text" placeholder="课程属性" value={newCourseAttribute} onChange={(e) => setnewCourseAttribute(e.target.value)} />
                                                                        </div>
                                                                        <div className="mb-3">
                                                                            <label className="form-label" htmlFor="name">学分</label>
                                                                            <input className="form-control item" id="name" type="nuber" placeholder="学分" value={newCredit} onChange={(e) => setnewCredit(e.target.value)} />
                                                                        </div>
                                                                        <div className="mb-3">
                                                                            <label className="form-label" htmlFor="name">学时</label>
                                                                            <input className="form-control item" id="name" type="nuber" placeholder="学时" value={newContactHour} onChange={(e) => setnewContactHour(e.target.value)} />
                                                                        </div>
                                                                        <div className="mb-3">
                                                                            <label className="form-label" htmlFor="name">开设学期</label>
                                                                            <input className="form-control item" id="name" type="nuber" placeholder="开设学期" value={newSemesterOffered} onChange={(e) => setnewSemesterOffered(e.target.value)} />
                                                                        </div>
                                                                        <div className="mb-3">
                                                                            <label className="form-label" htmlFor="name">考试成绩占比</label>
                                                                            <input className="form-control item" id="name" type="nuber" placeholder="考试成绩占比" value={newGradeScale} onChange={(e) => setnewGradeScale(e.target.value)} />
                                                                        </div>

                                                                        <div className="mb-3 mt-4">
                                                                            <button className="btn btn-primary btn-lg d-block w-100" onClick={updateCourse}>更新</button>
                                                                        </div>
                                                                    </div>
                                                                )}


                                                            </div>
                                                        </div>
                                                    </div>
                                                </section>
                                            </main>
                                        </div>
                                    </div>
                                </div>
                                <div className="app-footer">
                                    <span>
                                        © Bootstrap Gallery 2023
                                    </span>
                                </div>
                            </div>
                        </div>

                    </div>
                </div>
            )}
        </div>
    );
}
export default Admin_CourseManage;